package com.buercorp.wangyu.socket.tcpdemo04;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

public class Myrunnable implements Runnable{
    Socket socket;
    public Myrunnable(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            // 读取数据并保存在本地文件中
            BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
            // UUID 生成 随机的 文件名
            String name = UUID.randomUUID().toString().replace("-", "");
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("src\\main\\resources\\serverdir\\" + name + ".jpg"));
            int len;
            byte[] bytes = new byte[1024];
            while ((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
            }
            // 回写数据
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bw.write("上传成功");
            bw.newLine();
            // 用于清空BufferedWriter的缓冲区并强制写入所有剩余字符
            bw.flush();


        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            // 释放资源
            if (socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }


        }
    }
}
